#!/bin/bash

# usage: ./stack-test test4.2

set -e -u

export SCRIPT=$1

unameOut="$(uname -s)"
case "${unameOut}" in
    Linux*)     machine=Linux;;
    Darwin*)    machine=Darwin;;
    CYGWIN*)    machine=Cygwin;;
    MINGW*)     machine=MinGw;;
    *)          machine="UNKNOWN:${unameOut}"
esac
echo "We are on a ${machine} machine"

if test "${machine}" == "Darwin" ; then
  EXTRA_GHC_OPTIONS="--ghc-options=-optl-Wl,-dead_strip_dylibs"
else
  EXTRA_GHC_OPTIONS=""
fi

kill_cardano_nodes () {
  # Use a shorter name here (Linux ps only prints this much).
  targets=$(ps | grep -v grep | grep cardano-node-si | sed 's/^[ ]*//;s/ .*//')
  if test -n "${targets}" ; then
    kill -INT ${targets}
  fi

}

# Kill all existing cardano-node-simple processes. If there are processes
# still running from previous runs of this script, the test will fail if
# we don't kill them first.
kill_cardano_nodes

pushd ..
stack build $EXTRA_GHC_OPTIONS cardano-sl-script-runner cardano-sl-node cardano-sl-tools
export PATH=$(realpath $(stack path --local-install-root)/bin):$PATH
popd

CFG=$(realpath ../lib/configuration.yaml)
LOGCFG=$(realpath ./log-config.yaml)
TOPO=$(realpath ./topology-local.yaml)
POLFILE=$(realpath ../scripts/policies/policy_script-runner.yaml)

if test "${machine}" == "Darwin" ; then
  tmpdir=$(mktemp -d -t testrun)
else
  tmpdir=$(mktemp -d -p . testrun-XXXXXX)
fi

echo "Temp directory: $tmpdir"
cd $tmpdir
mkdir test-state

testcases --log-console-off --no-brickui --configuration-file $CFG \
  --db-path test-state/db --keyfile secret.key --log-config $LOGCFG \
  --logs-prefix test-state/logs --topology $TOPO --policies $POLFILE

kill_cardano_nodes

egrep --color=always \
  "Processing of proposal|We'll request data for key Tagged|Ignoring data|Proposal .* is confirmed" \
  test-state/relay-stdout-0


